package org.invigorare.auctions.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * See {@link SynchronizableInboundDataOpener} and {@link SynchronizableOutboundDataOpener}
 * for details.
 * @author jchern
 *
 */
public abstract class SynchronizableDataOpener extends SQLiteOpenHelper {

	public static final String _ROW_ID_ = "ROWID";
	
	/** Pass-through constructor **/
	public SynchronizableDataOpener(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}

	protected String createTableString(String tableName, ColBinding[] columns)
	{
		StringBuffer sb = new StringBuffer();
	
		// Start SQL command
		sb.append("CREATE TABLE ");
		sb.append(tableName);
		sb.append(" (");
		
		// Loop over columns
		for (int i = 0; i < columns.length; i++) {
			ColBinding col = columns[i];
			sb.append(col.name);
			sb.append(' ');
			sb.append(col.type);
			
			if (i != columns.length - 1) 
				sb.append(", ");
		}
		
		// Complete SQL command
		sb.append(");");
		
		return sb.toString();
	}
	
	/** Column name and type binding */
	protected static class ColBinding {
		final String name, type;
		public ColBinding(String name, String type) {
			this.name = name;
			this.type = type;
		}
	}
	
	/**
	 * Returns a new array with the given column definition appended
	 * to the contents of the existing array
	 * @param columns
	 * @param toAdd
	 * @return
	 */
	protected static ColBinding[] appendColumnDef(ColBinding[] columns, ColBinding toAdd) {
		ColBinding[] appended = new ColBinding[columns.length + 1];
		System.arraycopy(columns, 0, appended, 0, columns.length);
		appended[columns.length] = toAdd;
		return appended;
	}
	
}
